package net.da.processor;

import net.da.core.bof.ApplicationSession;
import net.da.services.SecurityService;
import net.da.services.SessionExpiredException;

import com.google.inject.Inject;

public abstract class AbstractProcessor<T extends IOResponse, E extends IORequest> implements IOProcessor<T, E> {

    @Inject
    private SecurityService securityService;

    public T processRequest(E request, String authorizationCode) {
        ApplicationSession session = null;
        if (authorizationCode != null) {
            try {
                session = securityService.getSessionByAuthorizationCode(authorizationCode);
                return process(request, session);
            } catch (SessionExpiredException e) {
                T sessionWasExpiredResponse = buildIOResponseEmptyInstance();
                session = securityService.authenticateGuestUser();
                String guestAuthorizationCode = session.getAuthorizationCode();
                SessionExpiredError error = new SessionExpiredError();
                // error.setMessage(e.getLocalizedMessage());
                sessionWasExpiredResponse.addError(error);
                sessionWasExpiredResponse.setAuthorizationCode(guestAuthorizationCode);
                return sessionWasExpiredResponse;
            }
        } else {
            T emptyAuthorizationCodeResponse = buildIOResponseEmptyInstance();
            session = securityService.authenticateGuestUser();
            emptyAuthorizationCodeResponse.setAuthorizationCode(session.getAuthorizationCode());
            return emptyAuthorizationCodeResponse;
        }
    }

    protected abstract T process(E request, ApplicationSession session);

    protected abstract T buildIOResponseEmptyInstance();
}
